MODULE resize
  !-----------------------------------------------------------
  ! KRUUNUNHAKA basis set tool kit - memory reallocation routines
  !-----------------------------------------------------------
  ! See CHANGELOG
  !-----------------------------------------------------------
  ! Copyright (C) 2003-2008 Pekka Manninen, 2010 Jussi Lehtola
  !
  ! This program is distributed under the terms of the GNU General
  ! Public License as published by the Free Software Foundation;
  ! either version 2 of the License, or (at your option) any later version.
  !
  ! This program is distributed in the hope that it will be useful,
  ! but WITHOUT ANY WARRANTY; without even the implied warranty of
  ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
  !
  ! Please note that this program as well as its 
  ! author must be properly cited whenever the program or some parts 
  ! originated on it are employed. 
  !
  !-----------------------------------------------------------

  USE definitions

  IMPLICIT NONE
CONTAINS

  SUBROUTINE resize_XlCl(nbas,X_l,C_l,nmax)
    IMPLICIT NONE
    ! Exponents
    REAL(KIND=prec), DIMENSION(:,:), ALLOCATABLE, INTENT(INOUT) :: X_l
    ! Coefficients
    REAL(KIND=prec), DIMENSION(:,:,:), ALLOCATABLE, INTENT(INOUT) :: C_l
    ! Number of exponents and contractions in every shell
    INTEGER, DIMENSION(MAXL,2), INTENT(INOUT) :: nbas

    ! New maximum size for arrays
    INTEGER, INTENT(IN) :: nmax
    
    ! Helper arrays
    REAL(KIND=prec), DIMENSION(:,:), ALLOCATABLE :: Xlhelp
    REAL(KIND=prec), DIMENSION(:,:,:), ALLOCATABLE :: Clhelp

    ! Loop index
    INTEGER :: l

    ! First check if arrays are allocated at all
    IF(.NOT. ALLOCATED(X_l) .AND. .NOT. ALLOCATED(C_l)) THEN
       ALLOCATE(X_l(MAXL,nmax))
       ALLOCATE(C_l(MAXL,nmax,nmax))
       X_l = 0
       C_l = 0
       RETURN
    END IF

    ! If arrays are already correctly sized, do nothing.
    IF(nmax<SIZE(X_l,2)) THEN
       RETURN
    END IF

    ! Allocate helpers
    ALLOCATE(Xlhelp(MAXL,MAXVAL(nbas(:,1))))
    ALLOCATE(Clhelp(MAXL,MAXVAL(nbas(:,1)),MAXVAL(nbas(:,2))))

    Xlhelp=0.0_prec
    Clhelp=0.0_prec

    ! Copy shells
    DO l=1,MAXL
       Xlhelp(l,1:nbas(l,1))=X_l(l,1:nbas(l,1))
       Clhelp(l,1:nbas(l,1),1:nbas(l,2))=C_l(l,1:nbas(l,1),1:nbas(l,2))
    END DO

    ! Make original arrays bigger
    DEALLOCATE(X_l)
    DEALLOCATE(C_l)

    ALLOCATE(X_l(MAXL,nmax))
    ALLOCATE(C_l(MAXL,nmax,nmax))

    X_l=0.0_prec
    C_l=0.0_prec


    ! Copy back shells
    DO l=1,MAXL
       X_l(l,1:nbas(l,1))=Xlhelp(l,1:nbas(l,1))
       C_l(l,1:nbas(l,1),1:nbas(l,2))=Clhelp(l,1:nbas(l,1),1:nbas(l,2))
    END DO

    ! Free memory
    DEALLOCATE(Xlhelp)
    DEALLOCATE(Clhelp)
  END SUBROUTINE resize_XlCl
END MODULE resize
